package com.yj.web.help;

import com.yj.web.dao.mapper.OperationRoleMapper;
import com.yj.web.dao.mapper.ViewRoleMapper;
import com.yj.web.dao.po.admin.OperationRole;
import com.yj.web.dao.po.admin.ViewRole;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.*;

/**
 * Created by yanlinyang on 2017/6/27.
 */
public class RoleMap {
    private static final Log logger = LogFactory.getLog(RoleMap.class);
    public static Map<Integer, Set<String>> VIEW_ROLE_MAP = new HashMap<>();
    public static Map<Integer, Set<String>> OPERATION_ROLE_MAP = new HashMap<>();

    public static Map<Integer, Set<String>> getViewRoleMap() {
        return VIEW_ROLE_MAP;
    }

    public static Map<Integer, Set<String>> getOperationRoleMap() {
        return OPERATION_ROLE_MAP;
    }

    static {
        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring/*.xml");
        ViewRoleMapper viewRoleMapper = (ViewRoleMapper) ac.getBean("viewRoleMapper");
        OperationRoleMapper operationRoleMapper = (OperationRoleMapper)ac.getBean("operationRoleMapper");

        try {
            List<ViewRole> viewRoles = viewRoleMapper.listViewRole();
            if (null != viewRoles) {
                for (ViewRole viewRole : viewRoles) {
                    if (VIEW_ROLE_MAP.containsKey(viewRole.getRoleNumber())) {
                        VIEW_ROLE_MAP.get(viewRole.getRoleNumber()).add(viewRole.getView());
                    } else {
                        Set<String> views = new HashSet<>();
                        views.add(viewRole.getView());
                        VIEW_ROLE_MAP.put(viewRole.getRoleNumber(), views);
                    }
                }
            }

            List<OperationRole> operationRoles = operationRoleMapper.listOperationRole();
            if (null != operationRoles) {
                for (OperationRole operationRole : operationRoles) {
                    if (OPERATION_ROLE_MAP.containsKey(operationRole.getRoleNumber())) {
                        OPERATION_ROLE_MAP.get(operationRole.getRoleNumber()).add(operationRole.getOperation());
                    } else {
                        Set<String> operations = new HashSet<>();
                        operations.add(operationRole.getOperation());
                        OPERATION_ROLE_MAP.put(operationRole.getRoleNumber(), operations);
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e);
        }
    }
}
